package com.laicunba.ext.service.impl;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.UUID;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.laicunba.ext.pojo.MiSportsVO;
import com.laicunba.ext.service.MiSportsService;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.HttpUtil;
import com.laicunba.util.StringUtil;

@Service
public class MiSportsServiceImpl implements MiSportsService {

	@Override
	public MiSportsVO getMiSportsVO(MiSportsVO miSportsVO) throws Exception {
		if(StringUtil.isEmpty(miSportsVO.getUrl())){
			miSportsVO.setErrorInfo("地址为空");
			return miSportsVO;
		}

		if(StringUtil.isEmpty(miSportsVO.getAppKey())){
			miSportsVO.setAppKey("0770060200881900");
		}

		if(StringUtil.isEmpty(miSportsVO.getAppSecret())){
			miSportsVO.setAppSecret("MGNmZTE0ZDhjN2MzZGQyMQ==");
		}

		miSportsVO.setNonceStr(create_nonce_str());
		miSportsVO.setTimestamp(create_timestamp());
		String string1 = "";
		String accessToken = manageAccessToken(miSportsVO.getAppKey(),miSportsVO.getAppSecret());
		miSportsVO.setAccessToken(accessToken);
		if(!"error".equals(accessToken) && StringUtil.isNotEmpty(accessToken)){
			// 注意这里参数名必须全部小写，且必须有序

			string1 = "access_token=" + miSportsVO.getAccessToken() + "&appkey=" + miSportsVO.getAppKey() + "&noncestr=" + miSportsVO.getNonceStr() + "&timestamp=" + miSportsVO.getTimestamp() + "&url=" + miSportsVO.getUrl();
			System.out.println(string1);

			try {
				MessageDigest crypt = MessageDigest.getInstance("SHA-1");
				crypt.reset();
				crypt.update(string1.getBytes("UTF-8"));
				miSportsVO.setSignature(byteToHex(crypt.digest()));
				miSportsVO.setErrorInfo("ok!");
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

		}else{
			miSportsVO.setErrorInfo("mi_sports_access_token is error or null!");
		}
		return miSportsVO;
	}

	public String manageAccessToken(String appKey,String appSecret) throws Exception{
		synchronized(this){
			String accessToken = CacheUtil.getAttribute("mi_sports_access_token");	
			if(StringUtil.isEmpty(accessToken)){
				getAccessToken(appKey, appSecret);
				accessToken = CacheUtil.getAttribute("accessToken");
				return accessToken;
			}else{
				return accessToken;
			}
		}
	}
	
	private static void getAccessToken(String appKey, String appSecret) throws Exception {
		JSONObject jsonObject = new JSONObject();
		String url = "https://aos-jsbridge.mi-ae.cn/v1/token?appkey=" + appKey + "&appsecret=" + appSecret;
//		 获得access_token 和expires_in
//		String token = "[" + HttpUtil.doGet(url1) + "]";
		jsonObject = JSONObject.fromObject(HttpUtil.doGet(url));
		int expiresIn = 0;
		String accessToken = "";
		if(jsonObject != null) {
			expiresIn = Integer.parseInt((String)jsonObject.get("expires_in"));
			accessToken = (String) jsonObject.get("access_token");
		}
		
		if (StringUtil.isNotEmpty(accessToken)) {
				CacheUtil.setAttribute("mi_sports_access_token", accessToken, expiresIn - 200);
		} else {
			CacheUtil.setAttribute("mi_sports_access_token", "error");
		}
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
}
